package com.kgc.util;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @author hyj
 * @time 2024/4/2 12:01
 * @describe
 */

public class SendEmailUtil {
    /**
     * 1.发件人的邮箱账号
     * 2.发件人的邮箱的授权码(自己在邮箱服务器中开启并设置)
     * 3.发件人邮箱的SMTP服务器地址
     * 4.将transport声明为类级别变量
     */
    public static String sendEmailAccount = "2820127094@qq.com";
    public static String sendEmailPassword = "fxbolhzkxgtjddda";
    public static String sendEmailSMTPHost = "smtp.qq.com";
    private Transport transport;

    /**
     * 发送邮件
     *
     * @param receiveMailAccount 收件人邮箱
     * @param mailContent        邮件内容
     */
    public void sendMail(String receiveMailAccount, String mailContent) {
        // 创建用于连接邮件服务器的参数配置
        Properties props = new Properties();
        // 设置使用SMTP协议
        props.setProperty("mail.transport.protocol", "smtp");
        // 设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", sendEmailSMTPHost);
        // 设置需要验证
        props.setProperty("mail.smtp.auth", "true");

        // 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        // 设置debug模式，便于查看发送过程所产生的日志
        session.setDebug(true);

        try {
            // 创建一封邮件
            MimeMessage message = createMimeMessage(session, sendEmailAccount, receiveMailAccount, mailContent);
            // 检查传输是否未连接
            if (transport == null || !transport.isConnected()) {
                transport = session.getTransport("smtp");
                transport.connect(sendEmailSMTPHost, sendEmailAccount, sendEmailPassword);
            }

            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param session     和服务器交互的会话
     * @param sendMail    发件人邮箱
     * @param receiveMail 收件人邮箱
     * @return 创建好的邮件对象
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String mailContent) throws Exception {
        // 创建一封邮件
        MimeMessage message = new MimeMessage(session);
        // 设置发件人姓名和编码格式
        message.setFrom(new InternetAddress(sendMail, "基于SSM的博客系统", "UTF-8"));
        // 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "尊敬的用户", "UTF-8"));
        // 设置邮件主题
        message.setSubject("邮箱提醒", "UTF-8");
        // 设置邮件正文
        message.setContent(mailContent, "text/html;charset=UTF-8");
        // 设置发件时间
        message.setSentDate(new Date());
        // 保存设置
        message.saveChanges();
        return message;
    }
}
